/*
 * -- HistoryAdapter.java --
 * 
 * Copyright 2011, Kyan He <kyan.ql.he@gmail.com>
 * 
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package im.kyan.android.googlefight;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class HistoryAdapter extends BaseAdapter {
    
    // stores all search actions
    private ArrayList<HistoryRecord> mHistoryRecords = new ArrayList<HistoryRecord>();
    
    private Context mContext;
    
    private LayoutInflater mInflater;
    
    private SQLiteDatabase mDatabase;
    
    public HistoryAdapter(Context ctx) {
        
        mContext = ctx;
        
        mDatabase = new HistoryDatabase(mContext).getWritableDatabase();
        
        mInflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        
        final Cursor c = mDatabase.query(HistoryDatabase.TABLE_NAME, null,
                null, null, null, null, null);
        if (c != null) {
            if (c.moveToFirst()) {
                do {
                    
                    final HistoryRecord r = createRecord(c.getString(1));
                    r.mId = c.getLong(0);
                    r.setRate(c.getLong(2));
                    r.setTimeStamp(c.getLong(3));
                    mHistoryRecords.add(0, r);
                    
                } while (c.moveToNext());
            }
            c.close();
        }
    }
    
    public int getCount() {
        return mHistoryRecords.size();
    }
    
    public Object getItem(int position) {
        return position;
    }
    
    public long getItemId(int position) {
        return position;
    }
    
    public View getView(int position, View convertView, ViewGroup parent) {
        
        View v = mInflater.inflate(R.layout.item_record, null);
        
        TextView keyView = (TextView) v.findViewById(R.id.key);
        TextView rateView = (TextView) v.findViewById(R.id.rate);
        TextView timeView = (TextView) v.findViewById(R.id.time);
        
        final HistoryRecord record = mHistoryRecords.get(position);
        
        keyView.setText(record.getKey());
        
        final long rate = record.getRate();
        final long ts = record.getTimeStamp();
        
        if (ts < 0 && rate < 0) {
            
            // rating
            rateView.setText("Rating...");
            timeView.setText("");
        } else if (rate < 0) {
            
            // cannot get available
            rateView.setText("Error");
            timeView.setText(DateFormat.format("hh:mm MMM dd", ts));
        } else {
            
            // success rate
            rateView.setText(getReadableLong(rate) + " results");
            timeView.setText(DateFormat.format("hh:mm MMM dd", ts));
        }
        
        return v;
    }
    
    static HistoryRecord createRecord(String key) {
        
        HistoryRecord r = new HistoryRecord();
        
        r.setKey(key);
        
        // @see getView(), ts < 0 && rate < 0 indicates rating in process
        r.setRate(-1);
        r.setTimeStamp(-1);
        
        return r;
    }
    
    void addRecord(HistoryRecord record) {
        
        mHistoryRecords.add(0, record);
        notifyDataSetChanged();
    }
    
    void updateRecord(HistoryRecord record) {
        
        final int i = mHistoryRecords.indexOf(record);
        if (i == -1) {
            Log.d("kyan", "record do not exist");
            return;
        }
        
        mDatabase.execSQL("INSERT INTO history(key,rate,timestamp) VALUES('"
                + record.getKey() + "', " + record.getRate() + ", "
                + record.getTimeStamp() + ")");
    }
    
    void deleteAll() {
        
        mHistoryRecords = null;
        mHistoryRecords = new ArrayList<HistoryRecord>();
        
        mDatabase.execSQL("delete from history");
    }
    
    static String getReadableLong(long l) {
        
        final String s = Long.toString(l);
        final int sz = s.length();
        int i = sz % 3;
        i = (i == 0) ? 3 : i;
        
        String str = s.substring(0, i);
        while (i < sz) {
            
            str += "," + s.substring(i, i + 3);
            i += 3;
        }
        
        return str;
    }
    
    /*
     * Item of History
     */
    static class HistoryRecord {
        
        /**
         * @see HistoryAdapter#createRecord(String)
         */
        private HistoryRecord() {
        }
        
        // identify item in db
        private long mId;
        
        // keyword of search
        private String mKey;
        
        // number of search results
        private long mRate;
        
        // time since epoch
        private long mTimeStamp;
        
        public String getKey() {
            return mKey;
        }
        
        public void setKey(String mKey) {
            this.mKey = mKey;
        }
        
        public long getRate() {
            return mRate;
        }
        
        public void setRate(long mRate) {
            this.mRate = mRate;
        }
        
        public long getTimeStamp() {
            return mTimeStamp;
        }
        
        public void setTimeStamp(long mTimeStamp) {
            this.mTimeStamp = mTimeStamp;
        }
    }
    
}